

 
 // 任务数据存储
var taskData = [
    {
        id: 1,
        _selected: false,
        name: 'monitor_real_time_logs',
        command: 'timeout 60 tail -f /var/log/syslog',
        mode: 'parallel',
        hosts: ['web-server-01', 'api-server-01'],
        status: '运行中',
        command_type: 'streaming',
        timeout: 60,
        expected: [{'pattern': 'active (running)', 'use_regex': false, 'match_times': 3}],
        unexpected: [{'pattern': 'failed21', 'use_regex': true, 'match_times': 2}],
        depends_on: ['restart_nginx_service'],
        allow_failure: true,
        interactive_response: [
            {prompt: 'Password:', response: 'root', times: 1}
        ],
        streaming_config: {
            max_duration: 30,
            line_timeout: 10,
            kill_timeout: 1,
            show_realtime: true,
            write_to_file: true,
            shell_inherit_task: '',
            shell_destroy: false
        }
    },
    {
        id: 2,
        _selected: false,
        name: 'demo',
        command: 'timeout 60 tail -f /var/log/syslog',
        mode: 'parallel',
        hosts: ['web-server-01', 'api-server-01'],
        status: '运行中',
        command_type: 'streaming',
        timeout: 60,
        expected: [{'pattern': 'active (running)', 'use_regex': false, 'match_times': 1}],
        unexpected: [{'pattern': 'failed21', 'use_regex': false, 'match_times': 1},
                     {'pattern': 'unexpected', 'use_regex': true, 'match_times': 3}
        ],
        depends_on: ['restart_nginx_service'],
        allow_failure: true,
        interactive_response: [
            {prompt: 'Password:', response: 'root', times: 1}
        ],
        streaming_config: {
            max_duration: 30,
            line_timeout: 10,
            kill_timeout: 1,
            show_realtime: true,
            write_to_file: true,
            shell_inherit_task: '',
            shell_destroy: false
        }
    },
];

var taskTableIns = null;

window.DataManager = {
    getTaskData: function() {
        return taskData;
    },
    getHostData: function() {
        return hostData;
    }
}

layui.use(['table', 'layer', 'form', 'element'], function(){
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            element = layui.element,
            $ = layui.$;

        // 当前操作状态
        var currentAction = '';
        var currentTaskId = null;

        // 渲染表格
        function renderTable() {
            taskTableIns = table.render({
                elem: '#taskTable',
                data: taskData,
                toolbar: '#taskToolbarDemo', // 开启头部工具栏
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: '序号', width: 80, sort: true, fixed: 'left', edit: 'text'},
                    {field: 'name', title: '任务名称', width: 200, edit: 'text'},
                    {field: 'command', title: '执行命令', minWidth: 250, edit: 'text'},
                    {field: 'command_type', title: '命令类型', width: 100, edit: 'select', selectList: {
                        'normal': 'normal (普通)',
                        'streaming': 'streaming (流式)',
                        // 'auto': 'auto (自动)',
                        'long_running': 'long_running (长时间运行)'
                    }},
                    {field: 'mode', title: '执行模式', width: 100, edit: 'select', selectList: {
                        'serial': 'serial (串行)',
                        'parallel': 'parallel (并行)'
                    }},
                    {field: 'hosts', title: '目标主机', width: 200, templet: '#hostsTpl'},
                    {field: 'status', title: '状态', width: 100, templet: '#taskStatusTpl'},
                    {title: '操作', toolbar: '#taskBarDemo', width: 180, fixed: 'right'}
                ]],
                skin: 'line', // 行边框风格
                even: true, // 开启隔行背景
                page: true, // 开启分页
                limits: [10, 15, 20, 25, 50, 100],
                limit: 15, // 每页默认显示的数量
                loading: false,
                text: {
                    none: '暂无相关数据'
                }
            });
        }

        // 重新加载表格数据
        function reloadTable() {
            taskTableIns.reload({
                data: taskData
            });
        }

        // 根据ID获取任务数据
        function getTaskById(id) {
            return taskData.find(function(task) {
                return task.id === id;
            });
        }

        // 清空表单
        function clearForm() {
            // $('#task_config')[0].reset();
            
            // 清空动态数组字段
            $('#name-input').html('<input type="text" name="name" placeholder="请输入任务名称" class="layui-input" value="">');
            $('#command-input').html('<textarea name="command" placeholder="请输入执行命令" class="layui-textarea"></textarea>');
            $('#hosts-container').html('<div class="array-item"><input type="text" name="hosts[]" placeholder="请输入主机名称" class="layui-input"><button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button></div>');
            
            $('#expected-container').html(`
                <div class="expected-block">
                    <div class="layui-form-item">
                        <label class="layui-form-label">匹配模式</label>
                        <div class="layui-input-block">
                            <input type="text" name="expected_pattern[]" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">是否使用正则表达式</label>
                            <div class="layui-inline">
                                <input type="checkbox" name="expected_use_regex[]" class="layui-input" lay-skin="switch" lay-text="是|否">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" >匹配次数</label>
                            <div class="layui-inline">
                                <input type="number" name="expected_match_times[]" class="layui-input" value="1">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                        </div>
                    </div>
                    
                </div>
            `);
            
            $('#unexpected-container').html(`
                <div class="unexpected-block">
                    <div class="layui-form-item">
                        <label class="layui-form-label">匹配模式</label>
                        <div class="layui-input-block">
                            <input type="text" name="unexpected_pattern[]" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">是否使用正则表达式</label>
                            <div class="layui-inline">
                                <input type="checkbox" name="unexpected_use_regex[]" class="layui-input" lay-skin="switch" lay-text="是|否">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" >匹配次数</label>
                            <div class="layui-inline">
                                <input type="number" name="unexpected_match_times[]" class="layui-input" value="0">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                        </div>
                    </div>
                </div>
            `);
            
            $('#depends-container').html('<div class="array-item"><input type="text" name="depends_on[]" placeholder="请输入依赖任务名称" class="layui-input"><button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button></div>');
            
            $('#interactive-container').html(`
                <div class="interactive-block">
                    <div class="layui-form-item">
                        <label class="layui-form-label">提示词</label>
                        <div class="layui-input-block">
                            <input type="text" name="interactive_prompt[]" placeholder="例如: Password:" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">响应内容</label>
                        <div class="layui-input-block">
                            <input type="text" name="interactive_response[]" placeholder="例如: root" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">响应次数</label>
                        <div class="layui-input-block">
                            <input type="number" name="interactive_times[]" placeholder="例如: 1" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn layui-btn-danger remove-interactive"><i class="layui-icon layui-icon-delete"></i> 删除此响应</button>
                        </div>
                    </div>
                </div>
            `);
            console.log("清空表单");
            form.render();
        }

        // 填充表单数据
        function fillForm(taskData) {
            console.log(taskData);

            // 基础信息
            $('input[name="name"]').val(taskData.name);
            $('textarea[name="command"]').val(taskData.command);
            $('select[name="mode"]').val(taskData.mode);
            $('select[name="command_type"]').val(taskData.command_type);
            $('input[name="timeout"]').val(taskData.timeout);

            // 主机列表
            $('#hosts-container').empty();
            if (taskData.hosts && taskData.hosts.length > 0) {
                taskData.hosts.forEach(function(host) {
                    $('#hosts-container').append(`
                        <div class="array-item">
                            <input type="text" name="hosts[]" placeholder="请输入主机名称" class="layui-input" value="${host}">
                            <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                        </div>
                    `);
                });
            }

            // 期望输出
            $('#expected-container').empty();
            if (taskData.expected && taskData.expected.length > 0) {
                taskData.expected.forEach(function(expected) {
                    $('#expected-container').append(`
                        <div class="expected-block">
                            <div class="layui-form-item">
                                <label class="layui-form-label">匹配模式</label>
                                <div class="layui-input-block">
                                    <input type="text" name="expected_pattern[]" class="layui-input" value="${expected.pattern}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">是否使用正则表达式</label>
                                    <div class="layui-inline">
                                        <input type="checkbox" name="expected_use_regex[]" class="layui-input" lay-skin="switch" lay-text="是|否" ${expected.use_regex ? 'checked' : ''}>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" >匹配次数</label>
                                    <div class="layui-inline">
                                        <input type="number" name="expected_match_times[]" class="layui-input" value="${expected.match_times}">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                                </div>
                            </div>
                        </div>
                    `);
                });
            }

            // 不期望输出
            $('#unexpected-container').empty();
            if (taskData.unexpected && taskData.unexpected.length > 0) {
                taskData.unexpected.forEach(function(unexpected) {
                    $('#unexpected-container').append(`
                        <div class="unexpected-block">
                            <div class="layui-form-item">
                                <label class="layui-form-label">匹配模式</label>
                                <div class="layui-input-block">
                                    <input type="text" name="unexpected_pattern[]" class="layui-input" value="${unexpected.pattern}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">是否使用正则表达式</label>
                                    <div class="layui-inline">
                                        <input type="checkbox" name="unexpected_use_regex[]" class="layui-input" lay-skin="switch" lay-text="是|否" ${unexpected.use_regex ? 'checked' : ''}>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" >匹配次数</label>
                                    <div class="layui-inline">
                                        <input type="number" name="unexpected_match_times[]" class="layui-input" value="${unexpected.match_times}">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                                </div>
                            </div>
                        </div>
                    `);
                });
            }

            // 依赖任务
            $('#depends-container').empty();
            if (taskData.depends_on && taskData.depends_on.length > 0) {
                taskData.depends_on.forEach(function(depend) {
                    $('#depends-container').append(`
                        <div class="array-item">
                            <input type="text" name="depends_on[]" placeholder="请输入依赖任务名称" class="layui-input" value="${depend}">
                            <button type="button" class="layui-btn layui-btn-danger remove-item"><i class="layui-icon layui-icon-delete"></i> 删除</button>
                        </div>
                    `);
                });
            }

            // 交互响应
            $('#interactive-container').empty();
            if (taskData.interactive_response && taskData.interactive_response.length > 0) {
                taskData.interactive_response.forEach(function(interact) {
                    $('#interactive-container').append(`
                        <div class="interactive-block">
                            <div class="layui-form-item">
                                <label class="layui-form-label">提示词</label>
                                <div class="layui-input-block">
                                    <input type="text" name="interactive_prompt[]" placeholder="例如: Password:" class="layui-input" value="${interact.prompt}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">响应内容</label>
                                <div class="layui-input-block">
                                    <input type="text" name="interactive_response[]" placeholder="例如: root" class="layui-input" value="${interact.response}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">响应次数</label>
                                <div class="layui-input-block">
                                    <input type="number" name="interactive_times[]" placeholder="例如: 1" class="layui-input" value="${interact.times}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button type="button" class="layui-btn layui-btn-danger remove-interactive"><i class="layui-icon layui-icon-delete"></i> 删除此响应</button>
                                </div>
                            </div>
                        </div>
                    `);
                });
            }

            $('input[name="allow_failure"]').prop('checked', taskData.allow_failure);

            // 流式配置
            $('input[name="max_duration"]').val(taskData.streaming_config.max_duration);
            $('input[name="line_timeout"]').val(taskData.streaming_config.line_timeout);
            $('input[name="kill_timeout"]').val(taskData.streaming_config.kill_timeout);
            $('input[name="show_realtime"]').prop('checked', taskData.streaming_config.show_realtime);
            $('input[name="write_to_file"]').prop('checked', taskData.streaming_config.write_to_file);
            $('input[name="shell_inherit_task"]').val(taskData.streaming_config.shell_inherit_task);
            $('input[name="shell_destroy"]').prop('checked', taskData.streaming_config.shell_destroy);

            console.log("填充表单数据");
            form.render();
        }

        // 收集表单数据
        function collectFormData() {
            var formData = {
                name: $('input[name="name"]').val(),
                command: $('textarea[name="command"]').val(),
                mode: $('select[name="mode"]').val(),
                command_type: $('select[name="command_type"]').val(),
                timeout: parseInt($('input[name="timeout"]').val()) || 30,
                hosts: [],
                expected: [],
                unexpected: [],
                depends_on: [],
                interactive_response: [],
                streaming_config:{
                    max_duration: parseInt($('input[name="max_duration"]').val()) || 60,
                    line_timeout: parseInt($('input[name="line_timeout"]').val()) || 5,
                    kill_timeout: parseInt($('input[name="kill_timeout"]').val()) || 1,
                    show_realtime: $('input[name="show_realtime"]').is(':checked'),
                    write_to_file: $('input[name="write_to_file"]').is(':checked'),
                    shell_inherit_task: $('input[name="shell_inherit_task"]').val(),
                    shell_destroy: $('input[name="shell_destroy"]').is(':checked'),
                },      
                allow_failure: $('input[name="allow_failure"]').is(':checked'),
                status: '未运行'
            };

            // 收集主机列表
            $('input[name="hosts[]"]').each(function() {
                var value = $(this).val().trim();
                if (value) {
                    formData.hosts.push(value);
                }
            });

            // 收集期望输出
            // $('input[name="expected[]"]').each(function() {
            //     var value = $(this).val().trim();
            //     if (value) {
            //         formData.expected.push(value);
            //     }
            // });
            $('.expected-block').each(function() {
                var pattern = $(this).find('input[name="expected_pattern[]"]').val().trim();
                var use_regex = $(this).find('input[name="expected_use_regex[]"]').is(':checked');
                var match_times = parseInt($(this).find('input[name="expected_match_times[]"]').val()) || 1;
                if (pattern) {
                    formData.expected.push({
                        pattern: pattern,
                        use_regex: use_regex,
                        match_times: match_times
                    });
                }
            });


            // 收集不期望输出
            // $('input[name="unexpected[]"]').each(function() {
            //     var value = $(this).val().trim();
            //     if (value) {
            //         formData.unexpected.push(value);
            //     }
            // });
            $('.unexpected-block').each(function() {
                var pattern = $(this).find('input[name="unexpected_pattern[]"]').val().trim();
                var use_regex = $(this).find('input[name="unexpected_use_regex[]"]').is(':checked');
                var match_times = parseInt($(this).find('input[name="unexpected_match_times[]"]').val()) || 1;
                if (pattern) {
                    formData.unexpected.push({
                        pattern: pattern,
                        use_regex: use_regex,
                        match_times: match_times
                    });
                }
            });

            // 收集依赖任务
            $('input[name="depends_on[]"]').each(function() {
                var value = $(this).val().trim();
                if (value) {
                    formData.depends_on.push(value);
                }
            });

            // 收集交互响应
            $('.interactive-block').each(function() {
                var prompt = $(this).find('input[name="interactive_prompt[]"]').val();
                var response = $(this).find('input[name="interactive_response[]"]').val();
                var times = parseInt($(this).find('input[name="interactive_times[]"]').val()) || 1;
                
                if (prompt && response) {
                    formData.interactive_response.push({
                        prompt: prompt,
                        response: response,
                        times: times
                    });
                }
            });

            return formData;
        }

        // 验证表单数据
        function validateForm(formData) {
            if (!formData.name) {
                layer.msg('请输入任务名称', {icon: 2});
                return false;
            }
            if (!formData.command) {
                layer.msg('请输入执行命令', {icon: 2});
                return false;
            }
            return true;
        }


        // 监听头工具栏事件
        table.on('toolbar(taskTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    currentAction = 'add';
                    currentTaskId = null;
                    
                    layer.open({
                        type: 1,
                        title: '添加任务',
                        content: $('#taskFormModal'),
                        area: ['900px', '90%'],
                        maxmin: true,
                        success: function() {
                            clearForm();
                        }
                    });
                    break;
                case 'batchDelete':
                    var data = checkStatus.data;
                    if(data.length === 0){
                        layer.msg('请选择要删除的数据');
                    } else {
                        layer.confirm('确定删除选中的任务吗？', function(index){
                            // 删除选中的数据
                            data.forEach(function(item) {
                                taskData = taskData.filter(function(task) {
                                    return task.id !== item.id;
                                });
                            });
                            
                            reloadTable();
                            layer.close(index);
                            layer.msg('删除成功');
                        });
                    }
                    break;
            }
        });

        // 监听行工具事件
        table.on('tool(taskTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这个任务吗？', function(index){
                    taskData = taskData.filter(function(task) {
                        return task.id !== data.id;
                    });
                    reloadTable();
                    layer.close(index);
                    layer.msg('删除成功');
                });
            } else if(obj.event === 'edit'){
                currentAction = 'edit';
                currentTaskId = data.id;
                var task = getTaskById(currentTaskId);
                
                layer.open({
                    type: 1,
                    title: '编辑任务',
                    content: $('#taskFormModal'),
                    area: ['900px', '90%'],
                    maxmin: true,
                    success: function() {
                        fillForm(task);
                    }
                });
            } else if(obj.event === 'detail'){
                layer.open({
                    type: 1,
                    title: '任务详情',
                    content: '<div style="padding: 20px;"><pre>' + generateTaskYaml(data) + '</pre></div>',
                    area: ['600px', '500px']
                });
            }
        });

        // 监听单元格编辑
        table.on('edit(taskTable)', function(obj){
            var value = obj.value,
                data = obj.data,
                field = obj.field;
            
            // 更新数据
            var index = taskData.findIndex(function(task) {
                return task.id === data.id;
            });
            
            if (index !== -1) {
                taskData[index][field] = value;
                layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
            }
        });

        // 监听任务表格复选框选择事件
        table.on('checkbox(taskTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;

            for (let i = 0; i < taskData.length; i++) {
                taskData[i]._selected = false;
            }

            data.forEach(function(item) {
                var index = taskData.findIndex(function(task) {
                    return task.id === item.id;
                });
                if (index !== -1) {
                    taskData[index]._selected =true;
                }
            });
        });

        // 监听全选
        table.on('checkboxAll(taskTable)', function(obj){
            console.log(obj);

            // if(obj.checked){
            //     taskData.forEach(task => {
            //         task._selected = true;
            //     });
            // } else {
            //     taskData.forEach(task => {
            //         task._selected = false;
            //     });
            // }
        });



        // 表单提交按钮事件
        $(document).on('click', '#submit-btn', function() {
            var formData = collectFormData();
            
            if (!validateForm(formData)) {
                return;
            }
            
            if (currentAction === 'add') {
                // 添加任务
                var maxId = taskData.length > 0 ? Math.max.apply(Math, taskData.map(function(task) {
                    return task.id;
                })) : 0;
                formData.id = maxId + 1;
                
                taskData.push(formData);
                layer.msg('任务添加成功', {icon: 1});
            } else if (currentAction === 'edit') {
                // 编辑任务
                formData.id = currentTaskId;
                var index = taskData.findIndex(function(task) {
                    return task.id === currentTaskId;
                });
                
                if (index !== -1) {
                    taskData[index] = formData;
                    layer.msg('任务修改成功', {icon: 1});
                }
            }
            
            reloadTable();
            layer.closeAll();
        });

        // 重置表单按钮事件
        $(document).on('click', '#reset-btn', function() {
            layer.confirm('确定要重置表单吗？', {icon: 3, title:'重置确认'}, function(index){
                if (currentAction === 'edit') {
                    var task = getTaskById(currentTaskId);
                    fillForm(task);
                } else {
                    clearForm();
                }
                layer.close(index);
            });
        });

        
        // 搜索功能
        $('#searchInput').on('input', function() {
            var searchTerm = $(this).val().toLowerCase();
            if (searchTerm === '') {
                reloadTable();
            } else {
                var filteredData = taskData.filter(function(task) {
                    return task.name.toLowerCase().includes(searchTerm) || 
                        task.command.toLowerCase().includes(searchTerm) ||
                        task.mode.toLowerCase().includes(searchTerm) ||
                        (task.hosts && task.hosts.join(' ').toLowerCase().includes(searchTerm));
                });
                
                taskTableIns.reload({
                    data: filteredData
                });
            }
        });


        // 初始化表格
        renderTable();
    });



 // json 转 yaml
function generateTaskYaml(task) {
    // 生成任务配置
    var yaml = '';

    yaml += `  - name: "${task.name}"\n`;
    yaml += `    command: "${task.command.replace(/\n/g, ' ')}"\n`;
    
    if(task.mode && task.mode !== 'serial') {
        yaml += `    mode: "${task.mode}"\n`;
    }
    
    if(task.timeout && task.timeout !== 30) {
        yaml += `    timeout: ${task.timeout}\n`;
    }
    
    if(task.hosts && task.hosts.length > 0) {
        yaml += `    hosts:\n`;
        task.hosts.forEach(function(host) {
            yaml += `      - "${host}"\n`;
        });
    }
    
    if(task.expected && task.expected.length > 0) {
        yaml += `    expected:\n`;
        task.expected.forEach(function(item) {
            yaml += `      - pattern: "${item.pattern}"\n`;
            if(item.use_regex) {
                yaml += `        use_regex: true\n`;
            }
            if(item.match_times!=1) {
                yaml += `        match_times: ${item.match_times}\n`;
            }

        });
    }
    
    if(task.unexpected && task.unexpected.length > 0) {
        yaml += `    unexpected:\n`;
        task.unexpected.forEach(function(item) {
            yaml += `      - pattern: "${item.pattern}"\n`;
            if(item.use_regex) {
                yaml += `        use_regex: true\n`;
            }
            if(item.match_times!=0) {
                yaml += `        match_times: ${item.match_times}\n`;
            }

        });
    }
    
    if(task.depends_on && task.depends_on.length > 0) {
        yaml += `    depends_on:\n`;
        task.depends_on.forEach(function(item) {
            yaml += `      - "${item}"\n`;
        });
    }
    
    if(task.interactive_response && task.interactive_response.length > 0) {
        yaml += `    interactive_response:\n`;
        task.interactive_response.forEach(function(res) {
            yaml += `      - prompt: "${res.prompt}"\n`;
            yaml += `        response: "${res.response}"\n`;
            if(res.reply_times) {
                yaml += `        reply_times: ${res.reply_times}\n`;
            }else{
                yaml += `        reply_times: 1\n`;
            }
        });
    }
    
    if(task.allow_failure) {
        yaml += `    allow_failure: true\n`;
    }
    
    if(task.command_type) {
        yaml += `    command_type: "${task.command_type}"\n`;
    }
    if (task.command_type && task.command_type === 'streaming') {
    
        if(task.streaming_config  && Object.keys(task.streaming_config).length > 0) {

            yaml += `    streaming_config:\n`;
            var stream = task.streaming_config;
            if(stream.max_duration) yaml += `      max_duration: ${stream.max_duration}\n`;
            if(stream.line_timeout) yaml += `      line_timeout: ${stream.line_timeout}\n`;
            if(stream.kill_timeout) yaml += `      kill_timeout: ${stream.kill_timeout}\n`;
            if(stream.show_realtime !== undefined) yaml += `      show_realtime: ${stream.show_realtime}\n`;
            if(stream.write_to_file !== undefined) yaml += `      write_to_file: ${stream.write_to_file}\n`;
            if(stream.shell_inherit_task) yaml += `      shell_inherit_task: "${stream.shell_inherit_task}"\n`;
            if(stream.shell_destroy !== undefined) yaml += `      shell_destroy: ${stream.shell_destroy}\n`;
        }
    }
    
    yaml += '\n';
    
    return yaml;
}